package com.sy.olddriver.filter;

import com.sy.olddriver.constant.AppConstant;
import com.sy.olddriver.entity.User;
import com.sy.olddriver.utils.HttpUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用来统一判断当前用户是否是一个已经登录的状态
 *
 * @author Administrator
 */
public class UserStateFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //获取当前请求对应的URI
        String uri = HttpUtils.getMappingUri(req);
        //如果当前请求需要验证是否登录
        if (AppConstant.URIS_WITH_SESSION.contains(uri)) {
            User user = HttpUtils.getLoginUser();
            //如果用户没有登录，直接返回一个尚未登录的状态给前端
            if (null == user) {
                HttpUtils.writeJson(res, HttpUtils.buildFailure("当前用户尚未登录"));
            }
            //如果用户已经登录，直接放行
            else {
                chain.doFilter(req, res);
            }
        }
        //如果不需要登录则直接放行
        else {
            chain.doFilter(req, res);
        }

    }

    @Override
    public void destroy() {

    }
}
